<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('import_excel')" -->
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/importExcel')"
          >excel导入</el-button>
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('export_excel')" -->
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="hExportExcel"
          >excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employees" :default-sort="{prop: 'workNumber'}">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="scope">
              <!-- {{ scope.row.formOfEmployment === 1 ? '正式' : '非正式' }} -->
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[5,10,20]"
            layout="total, sizes, prev, pager, next"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      v-if="showDialog"
      :visible.sync="showDialog"
      title="新增员工"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <EmpDialog
        @success="hSuccess"
      />
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      v-if="showDialogRole"
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <AssignRole :cur-id="id" @close="showDialogRole = false" />
    </el-dialog>
  </div>
</template>
<script>
// import PageTools from '@/components/PageTools/index.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import { TYPE_MAP } from '@/constant/index'
import EmpDialog from './EmpDialog.vue'
import AssignRole from './assignRole.vue'
export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      employees: [],
      // 分页
      total: 0,
      page: 1,
      size: 10,
      // 新增子组件
      showDialog: false,
      showDialogRole: false, // 分配角色
      id: '' // 当前分配角色的员工id
    }
  },
  created() {
    // 获取员工列表
    this.loadEmployee()
  },
  methods: {
    // 聘用形式格式化
    format(type) {
      return TYPE_MAP[type]
      // if (type === 1) {
      //   return '正式'
      // } else if (type === 2) {
      //   return '非正式'
      // } else if (type === 3) {
      //   return 'AAA'
      // } else if (type === 4) {
      //   return 'BBB'
      // } else if (type === 5) {
      //   return 'CCC'
      // }
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployee()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      this.page = 1
      // 2. 重发请求
      this.loadEmployee()
    },
    // 获取员工列表
    async loadEmployee() {
      const res = await getEmployee({ page: this.page, size: this.size })
      console.log('员工信息', res)
      // 保存数据
      this.employees = res.data.rows
      this.total = res.data.total
    },
    // 用户点击删除
    hDel(id) {
      // 弹框确认删除
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    async doDel(id) {
      // 发送请求
      await delEmployee(id)
      // 提示成功
      this.$message.success('删除成功')
      // 删除最后一条数据，页码减一
      if (this.employees.length === 1 && this.page > 1) {
        this.page--
      }
      // 重新获取员工信息
      this.loadEmployee()
    },
    // 子组件添加员工成功，通知父组件
    hSuccess() {
      // 关闭弹框
      this.showDialog = false
      // 添加成功之后，跳到最后一页查看添加数据
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 重新获取员工信息
      this.loadEmployee()
    },
    // 导出
    async hExportExcel() {
      // 1.发送请求拿数据
      const res = await getEmployee({ page: this.page, size: this.size })
      console.log('员工信息', res)
      // 2.对数据进行格式转换
      const { header, data } = this.formatData(res.data.rows)
      console.log('结果是', header, data)
      // 3.导出
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    formatData(rows) {
      const mapObj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      /**
       * rows:
       * [
       *   {mobile:'13612345678', username:'管理员',...}
       *   {mobile:'13612345678', username:'小王',...}
       * ]
       *
       * header: [手机，用户名]
       * data: [ ['13612345678','管理员'], [] ]
       */
      // 英文的表头
      const enHeader = Object.keys(rows[0])

      // 表头
      const header = enHeader.map(item => mapObj[item])

      // 内容
      const data = rows.map(obj => {
        // 聘用形式 1,2 ----> '正式'，'非正式'
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      console.log(header, data)

      return { header, data }
    },

    // 分配角色
    hAssignRole(id) {
      // 显示弹框
      this.showDialogRole = true
      // 保存id
      this.id = id
    }
  }
}
</script>
